#include "filesocket.h"
#include <QDebug>

FileSocket::FileSocket(QObject *parent) : QTcpServer(parent)
{
   fileNameSet = false;
}

FileSocket::~FileSocket(){
    delete socket;
}

void FileSocket::listenFor(){
    listen(QHostAddress::Any);
}

void FileSocket::incomingConnection(int socketDescriptor){

   // qDebug()<<"FileSocket::incomingConnection:"<<socketDescriptor;

    socket = new QTcpSocket(this);

    connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()), Qt::DirectConnection);
  //  connect(socket, SIGNAL(connected()), this, SLOT(socketConnected()), Qt::DirectConnection);

    if(NULL!=socket)
    socket->setSocketDescriptor(socketDescriptor);

     fileNameSet = false;

    this->close();
}

void FileSocket::sendList(const QByteArray &bytes){

    if(NULL!=socket)socket->write(bytes);
}

void FileSocket::sendFile(QString fileName){
    QFile file(fileName);
    QByteArray buffer;

    if(file.open(QIODevice::ReadOnly)){
       // qDebug () << "File opened";
    }

    buffer = file.readAll();
    if(NULL!=socket)
    socket->write(buffer);

    file.close();
}

void FileSocket::receiveFile(QString fileName){
    if(fileName.isEmpty())return;
   // qDebug() <<"FileSocket::receiveFile:"<< fileNameSet;
   this->fileName = fileName;
}

void FileSocket::readyRead(){

    if(fileNameSet){
        QFile file(fileName);
        if(!file.open(QIODevice::WriteOnly | QIODevice::Append)){
            qDebug() << file.errorString();
            return;
        } else {
           qDebug() << "File opened"<< fileName;
        }

       //  qDebug() << "FileSocket::readyRead() fileName"<<fileName;
         QByteArray buffer = socket->readAll();
         if(!fileName.isEmpty())
         {
             file.write(buffer);
         }
         file.close();

        if(!socket->isReadable()){
            fileNameSet = false;
            fileName    = "";
            socket->flush();
        }
    }
}

void FileSocket::SetfileNameSet(bool bIs)
{
    fileNameSet =  bIs;
}

void FileSocket::Setsocket(QTcpSocket *soc)
{
    socket = soc;

    connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()), Qt::DirectConnection);
  //  connect(socket, SIGNAL(connected()), this, SLOT(socketConnected()), Qt::DirectConnection);

     fileNameSet = false;
}

